<?php
namespace App\Models;
use Illuminate\Support\Facades\DB;
use App\Libraries\AppRefund;
class ShopRefund extends CommonModel {
	protected $table = 'shop_refund';
    private $refund_status = array(
        '1'=>'申请退款',
        '2'=>'退款成功',
        '3'=>'商家拒绝',
        '4'=>'客服介入',
        '5'=>'客服拒绝',
        '6'=>'用户取消'
    );
    private $refund_type = array(
        '1'=>'取消订单',
        '2'=>'仅退款',
        '3'=>'退货'
    );
    //退款列表信息
    public function detail(){
        $order_sn = $this->getAttribute('order_sn');
        $goods_id = $this->getAttribute('goods_id');
        $status = $this->getAttribute('status');
        $refund_amount = $this->getAttribute('refund_amount');
        $created_at = $this->getAttribute('created_at');
        $refund_type = $this->getAttribute('refund_type');
        $buyer_id = $this->getAttribute('buyer_id');


        //商家不处理自动退款结束时间
        $end_time = 0;
        if($status == 1){
            $deadline =  Config::key('order_store_refund_time')->value('value');
            $end_time = date('Y-m-d H:i:s',strtotime($created_at) + $deadline);
        }

        //订单商品处理
        $order_goods = ShopOrderGoods::where(['order_sn'=>$order_sn])
            ->select('goods_id','goods_spec','goods_type','refund_status','market_price','goods_name','store_id','goods_price','goods_image','goods_number')
            ->when($goods_id,function($query) use ($goods_id){
                $query->where(['goods_id'=>$goods_id]);
            })
            ->get()
            ->groupBy('store_id')->toArray();

        $all_number = ShopOrderGoods::where(['order_sn'=>$order_sn])
            ->when($goods_id,function($query) use ($goods_id){
                $query->where(['goods_id'=>$goods_id]);
            })
            ->count('*');

        foreach ($order_goods as $k=>$v){
            unset($order_goods[$k]);
            $order_goods[$k]['goods_list'] = $v;
            $order_goods[$k]['store_id'] = $k;
            $store_info = ShopStore::getStoreDetailById($k);
            $order_goods[$k]['uid']  = $store_info->uid;
            $order_goods[$k]['store_name'] = $store_info->store_name;
            $order_goods[$k]['store_mobile'] = $store_info->store_mobile;
        }

        foreach ($order_goods as $key=>$val){
            $result[] = $val;
        }

        $buyer_name = ClientUser::where(['id'=>$buyer_id])->value('username');
        $this->setAttribute('store_list',$result);
        $this->setAttribute('order_amount',$refund_amount);
        $this->setAttribute('store_list',$result);
        $this->setAttribute('all_number',$all_number);
        $this->setAttribute('end_time',$end_time);
        $this->setAttribute('refund_type',$this->refund_type[$refund_type]);
        $this->setAttribute('refund_status',$status);
        $this->setAttribute('buyer_name',$buyer_name);
        $this->setAttribute('status',6);
    }

    //其它退款详情
    public function other_detail(){
        $refund_status = $this->getAttribute('refund_status');
        $refund_sn = $this->getAttribute('refund_sn');
        $status_list = $this->getStatusList($refund_sn,$refund_status);

        //退款日志
        $log_list = ShopRefundLog::where(['refund_sn'=>$refund_sn])
            ->orderBy('id','asc')
            ->select('details','status','time','confirm_name')
            ->get()
            ->each(function($v,$k){
                $v->name = $this->refund_status[$v->status];
            });
        $this->setAttribute('log_list',$log_list);
        $this->setAttribute('status_list',$status_list);
    }
    /*
     *  退款
     *  @param string $refund_sn
     *  @param int $refund_status
     */
    private function getStatusList($refund_sn,$refund_status){
        $created_time = ShopRefundLog::where(['refund_sn'=>$refund_sn,'status'=>1])->value('time');
        switch ($refund_status){
            case 1:
                $status_list=[
                    0=>['name'=>'申请退款','time'=>$created_time],
                    1=>['name'=>'商家处理中','time'=>$created_time],
                    2=>['name'=>'待完成','time'=>'']
                ];
                break;
            case 2:
                $status2=ShopRefundLog::where(['refund_sn'=>$refund_sn,'status'=>2])->value('time');
                $status_list=[
                    0=>['name'=>'申请退款','time'=>$created_time],
                    1=>['name'=>'处理中','time'=>$created_time],
                    2=>['name'=>'退款成功','time'=>$status2]
                ];
                break;
            case 3:
                $status3=ShopRefundLog::where(['refund_sn'=>$refund_sn,'status'=>3])->value('time');
                $status_list=[
                    0=>['name'=>'申请退款','time'=>$created_time],
                    1=>['name'=>'商家处理中','time'=>$created_time],
                    2=>['name'=>'退款失败','time'=>$status3]
                ];
                break;
            case 4:
                $status4=ShopRefundLog::where(['refund_sn'=>$refund_sn,'status'=>3])->value('time');
                $status_list=[
                    0=>['name'=>'申请退款','time'=>$created_time],
                    1=>['name'=>'客服介入','time'=>$status4],
                    2=>['name'=>'待完成','time'=>'']
                ];
                break;
            case 5:
                $status4=ShopRefundLog::where(['refund_sn'=>$refund_sn,'status'=>3])->value('time');
                $status5=ShopRefundLog::where(['refund_sn'=>$refund_sn,'status'=>3])->value('time');
                $status_list=[
                    0=>['name'=>'申请退款','time'=>$created_time],
                    1=>['name'=>'客服介入','time'=>$status4],
                    2=>['name'=>'退款成功','time'=>$status5]
                ];
                break;
            case 6:
                $status6=ShopRefundLog::where(['refund_sn'=>$refund_sn,'status'=>6])->value('time');
                $status_list=[
                    0=>['name'=>'申请退款','time'=>$created_time],
                    1=>['name'=>'退款中','time'=>$created_time],
                    2=>['name'=>'用户取消','time'=>$status6]
                ];
                break;
            default:
                $status_list = [];
                break;
        }
        return $status_list;
    }


    //退款成功
    public function refund_success($refund_info,$confirm_name){
        $uid = $refund_info['uid'];
        $details = $confirm_name.'处理：订单退款成功';

        $create = ShopOrderLog::createOrderLog($uid, $refund_info['order_sn'], $details, $confirm_name, 1);
        if(!$create){
            throw new \Exception('更新订单日志失败');
        }
        $create = ShopRefundLog::createOrderLog($uid, $refund_info['refund_sn'], $details, $confirm_name, 2);
        if(!$create){
            throw new \Exception('更新退款日志失败');
        }
        $update = self::where(['refund_sn'=>$refund_info['refund_sn']])->update(['status'=>2]);
        if(!$update){
            throw new \Exception('更新退款状态失败');
        }
        //更新订单商品状态
        $create = ShopOrderGoods::where(['order_sn'=>$refund_info['order_sn']])
            ->when($refund_info->goods_id,function($query) use ($refund_info){
                $query->where(['goods_id'=>$refund_info['goods_id']]);
            })
            ->update(['refund_status'=>3]);
        if(!$create){
            throw new \Exception('更新订单商品状态失败');
        }

        //回滚库存
        $create=ShopOrderGoods::where(['order_sn'=>$refund_info['order_sn']])->get()->each(function($v,$k){
            if($v->goods_type==0) {
                return ShopGoods::rbackGoodsStock($v->goods_id, $v->goods_number);
            }else if($v->goods_type ==1){
                return ShopSeckillGoods::rbackGoodsStock($v->goods_id, $v->goods_number);
            }else if($v->godos_type == 2){
                return ShopGroupGoods::rbackGoodsStock($v->goods_id, $v->goods_number);
            }
        });
        if(!$create){
            throw new \Exception('回滚库存失败');
        }
        return true;
    }

    /*
     *  退款接口
     *  @param array $refund_info
     */
    public function AppRefund($refund_info,$confirm_name){
        if(!in_array($refund_info['status'],['1','4'])){
            throw new \Exception('订单状态有误');
        }

        $payment_info=ShopOrderPayment::where(['order_sn'=>$refund_info['order_sn']])->first();
        $payment_code = $payment_info->payment_code;

        if(!$payment_code){
            throw new \Exception('找不到支付单');
        }

        $param=array();
        $param['total_fee'] = $refund_info['order_amount'];
        $param['refund_fee'] = $refund_info['refund_amount'];
        $param['out_refund_no'] = $refund_info['refund_sn'];
        $param['transaction_id'] = $payment_info->pay_sn;
        $param['out_trade_no'] = $refund_info['order_sn'];
        $param['refund_desc'] = $refund_info['refund_reply'];

        $app = new AppRefund();
        $return = $app->$payment_code($param);

        if($return['result_code']=='SUCCESS'){
            //更新订单日志
            ShopRefund::refund_success($refund_info,$confirm_name);
        }else{
            throw new \Exception($return['err_code_des']);
        }
        return true;
    }
}